package com.hs.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hs.entity.pojo.Comment;
import com.hs.entity.pojo.Trend;
import com.hs.entity.pojo.TrendCollect;
import com.hs.entity.pojo.TrendLike;
import com.hs.service.CommentService;
import com.hs.service.TrendCollectService;
import com.hs.service.TrendLikeService;
import com.hs.service.TrendService;
import com.hs.utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 程序启动时把所有动态的评论数、点赞数、收藏数 存入redis
@Component
public class ViewCountRunner implements CommandLineRunner {


    @Resource
    private RedisCache redisCache;

    @Resource
    private TrendService trendService;

    @Resource
    private TrendLikeService trendLikeService;

    @Resource
    private TrendCollectService trendCollectService;

    @Resource
    private CommentService commentService;


    @Override
    public void run(String... args) {
        // 默认map
        Map<String, Integer> defaultMap = new HashMap<>();
        defaultMap.put("default-key", 0);


        List<Integer> trendIds = trendService.list().stream().map(Trend::getId).collect(Collectors.toList());

        // 动态评论数
        Map<String, Integer> trendCommentCountMap = trendIds.stream().collect(Collectors.toMap(Object::toString, trendId -> {
            LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            commentLambdaQueryWrapper.eq(Comment::getTrendId, trendId);
            return (int) commentService.count(commentLambdaQueryWrapper);
        }));

        redisCache.setCacheMap("pet:view:trendCommentCount:", trendCommentCountMap.isEmpty() ? defaultMap : trendCommentCountMap);


        // 动态点赞数
        Map<String, Integer> trendLikeCountMap = trendIds.stream().collect(Collectors.toMap(Object::toString, trendId -> {
            LambdaQueryWrapper<TrendLike> trendLikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            trendLikeLambdaQueryWrapper.eq(TrendLike::getTrendId, trendId);
            return (int) trendLikeService.count(trendLikeLambdaQueryWrapper);
        }));
        redisCache.setCacheMap("pet:view:trendLikeCount:", trendLikeCountMap.isEmpty() ? defaultMap : trendLikeCountMap);

        // 动态收藏数
        Map<String, Integer> trendCollectCountMap = trendIds.stream().collect(Collectors.toMap(Object::toString, trendId -> {
            LambdaQueryWrapper<TrendCollect> trendCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            trendCollectLambdaQueryWrapper.eq(TrendCollect::getTrendId, trendId);
            return (int) trendCollectService.count(trendCollectLambdaQueryWrapper);
        }));
        redisCache.setCacheMap("pet:view:trendCollectCount:", trendCollectCountMap.isEmpty() ? defaultMap : trendCollectCountMap);
    }
}
